<template>
  <div class="choose">
    <div class="shuffle-container">
      <div class="card" v-for="(card, index) in cards" :key="index" :style="getCardStyle(index)">
        <img src="http://117.72.17.45:5500/data/icons/cardback.png" alt="card" />
      </div>
    </div>
    
    <!-- 9秒后显示的视图 -->
    <div v-if="showAfterAnimation" class="after-animation-view">
      <div class="above-bottom-view">
        <div class="above-content">
          <div class="hint-text">鼠标悬浮显示详情，Enter键
            发现信息</div>
          <button class="confirm-btn" @click="handleConfirm">确认</button>
        </div>
      </div>
      <div class="bottom-view">
        <div class="charactor-images-container">
          <div 
            v-for="(imageUrl, index) in charactorImages" 
            :key="index" 
            class="charactor-image-item"
            :class="{ 'selected': selected === index, 'selected-teammate': teammate_selected === index }"
            @click="selectCharacter(index)"
          >
            <div class="owner-badge">{{ index < charactorLength[mypos - 1] ? '自' : '友' }}</div>
            <img :src="imageUrl" :alt="`角色${index + 1}`" class="charactor-image" />
          </div>
        </div>
      </div>
    </div>
    <!-- 左下角白色圆形问号 -->
    <div class="help-button">
        <span class="question-mark">?</span>
    </div>
  </div>
</template>

<script setup>
//这个组件只负责发按照每个人拿的牌数量发英雄牌。
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoomStore } from '@/stores/room'
import { charactors } from '@/charactors/data.js'
import ws from '@/services/websocket'

const roomStore = useRoomStore()
const cards = ref([])
// 控制9秒后视图的显示
const showAfterAnimation = ref(false)

// 获取全局变量
const room2v2 = roomStore.getRoom2V2()
const characArray = roomStore.characArray
const stantard = roomStore.stantard
const room_id = roomStore.room_id
//我的位置
const mypos = roomStore.mypos
//队友的位置
const teammatePos = 5 - mypos // 1<->4, 2<->3 映射
// 创建大小为4的数组，存储每个玩家的角色数量
const charactorLength = ref([0, 0, 0, 0])

// 获取当前用户的角色数组
const myCharactorArray = ref([])

// 存储角色图片URL的数组
const charactorImages = ref([])

// 选中的角色索引
const selected = ref(-1)
const teammate_selected = ref(-1)

// 监听 Enter 键
const onKeydown = (e) => {
  if (e.key === 'Enter') {
    console.log('Enter键被按下')
  }
}

// 被服务器通知正在选择的回调（队友选择）
const handleBeingChoose = (payload) => {
  if (!payload) return
  const cnum = payload.cnum
  if (cnum == null) return
  const index = Array.isArray(myCharactorArray.value)
    ? myCharactorArray.value.findIndex((v) => v === cnum)
    : -1
  if (index !== -1) {
    teammate_selected.value = index
    // 清除自己的选中高亮，避免冲突
    selected.value = -1
  }
}

// 创建17张扑克牌数组
onMounted(() => {
  cards.value = Array.from({ length: 17 }, (_, i) => i)
  
  // 计算每个玩家的角色数量
  for (let i = 0; i < 4; i++) {
    charactorLength.value[i] = characArray[i] ? characArray[i].length : 0
  }
  
  // 获取当前用户与队友的角色数组，并合并
  const selfArray = characArray[mypos - 1] || []
  const teammateArray = characArray[teammatePos - 1] || []
  myCharactorArray.value = [...selfArray, ...teammateArray]
  
  // 基于合并后的数组构造角色图片URL数组
  charactorImages.value = []
  myCharactorArray.value.forEach((charactorId) => {
    const charactorName = charactors.get(charactorId)
    if (charactorName) {
      const imageUrl = `http://117.72.17.45:5500/data/charactors/${charactorName}.webp`
      charactorImages.value.push(imageUrl)
    }
  })
  
  // 9秒后显示新视图
  setTimeout(() => {
    showAfterAnimation.value = true
  }, 9000)

  // 注册键盘监听
  window.addEventListener('keydown', onKeydown)

  // 绑定网络回调：genre=4, type="beingchoose"
  ws.on(4, 'beingchoose', handleBeingChoose)
})

// 卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('keydown', onKeydown)
  // 解绑网络回调
  ws.off(4, 'beingchoose')
})

// 计算每张牌应该发向哪个方向
const getCardDirection = (index) => {
  let cardCount = 0
  
  // 计算当前牌属于哪个玩家
  for (let i = 0; i < 4; i++) {
    const playerIndex = stantard[i] - 1 // stantard[i] 是1-4，需要转换为0-3
    const playerCardCount = charactorLength.value[playerIndex]
    
    if (index < cardCount + playerCardCount) {
      return i // 返回方向：0=下，1=右，2=上，3=左
    }
    cardCount += playerCardCount
  }
  
  return -1 // 余下的牌原地不动
}

// 选择角色函数
const selectCharacter = (index) => {
  selected.value = index
  //当选择角色的时候需要通知队友自己预选的角色
  console.log('选中角色索引:', selected.value)
  const cnum = myCharactorArray.value[index]
  if (cnum == null) return
  const rid = room_id || ''
  const pos = mypos || ''
  ws.send({
    genre: 4,
    type: 'prechoose',
    rid,
    pos,
    cnum,
  })
}

// 为每张牌设置不同的位置偏移和动画
const getCardStyle = (index) => {
  // 初始位置：17张牌平行排列，每张牌间隔10px
  const initialOffset = (index - 8) * 10; // 从-80px到+80px，每张牌间隔10px
  const direction = getCardDirection(index)
  
  return {
    left: `${50 + initialOffset}px`, // 50px是容器中心
    top: '0px',
    '--direction': direction, // 传递方向给CSS
  }
}

// 确认按钮处理
const handleConfirm = () => {
  console.log('确认当前选择:', { selected: selected.value, teammate_selected: teammate_selected.value })
}
</script>

<style scoped>
.choose {
  width: 100%;
  height: 100%;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}


.shuffle-container {
  position: relative;
  width: 200px;
  height: 280px;
}

.card {
  position: absolute;
  width: 100px;
  height: 140px;
  animation: shuffle 9s ease-in-out forwards;
  transform-origin: center;
}

.card img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

/* 发牌动画：0-0.5秒静止，0.5-2秒洗牌，2-5秒静止，5-7秒发牌，7-9秒静止，9秒后消失 */
@keyframes shuffle {
  0% {
    transform: translateX(var(--initial-x)) translateY(0) rotate(0deg);
    z-index: var(--z-index);
    opacity: 1;
  }
  5.56% { /* 0.5/9 * 100% */
    transform: translateX(var(--initial-x)) translateY(0) rotate(0deg);
    z-index: var(--z-index);
    opacity: 1;
  }
  22.22% { /* 2/9 * 100% */
    transform: translateX(0) translateY(0) rotate(0deg);
    z-index: 1;
    opacity: 1;
  }
  55.56% { /* 5/9 * 100% */
    transform: translateX(0) translateY(0) rotate(0deg);
    z-index: 1;
    opacity: 1;
  }
  77.78% { /* 7/9 * 100% */
    /* 根据方向移动到不同位置 */
    transform: translateX(var(--final-x)) translateY(var(--final-y)) rotate(0deg);
    z-index: 1;
    opacity: 1;
  }
  100% {
    /* 保持发牌位置，但透明度变为0 */
    transform: translateX(var(--final-x)) translateY(var(--final-y)) rotate(0deg);
    z-index: 1;
    opacity: 0;
  }
}

/* 为每张牌设置不同的初始位置和动画延迟 */
.card:nth-child(1) { 
  --initial-x: -80px;
  --z-index: 1;
  animation-delay: 0s; 
}
.card:nth-child(2) { 
  --initial-x: -70px;
  --z-index: 2;
  animation-delay: 0s; 
}
.card:nth-child(3) { 
  --initial-x: -60px;
  --z-index: 3;
  animation-delay: 0s; 
}
.card:nth-child(4) { 
  --initial-x: -50px;
  --z-index: 4;
  animation-delay: 0s; 
}
.card:nth-child(5) { 
  --initial-x: -40px;
  --z-index: 5;
  animation-delay: 0s; 
}
.card:nth-child(6) { 
  --initial-x: -30px;
  --z-index: 6;
  animation-delay: 0s; 
}
.card:nth-child(7) { 
  --initial-x: -20px;
  --z-index: 7;
  animation-delay: 0s; 
}
.card:nth-child(8) { 
  --initial-x: -10px;
  --z-index: 8;
  animation-delay: 0s; 
}
.card:nth-child(9) { 
  --initial-x: 0px;
  --z-index: 9;
  animation-delay: 0s; 
}
.card:nth-child(10) { 
  --initial-x: 10px;
  --z-index: 10;
  animation-delay: 0s; 
}
.card:nth-child(11) { 
  --initial-x: 20px;
  --z-index: 11;
  animation-delay: 0s; 
}
.card:nth-child(12) { 
  --initial-x: 30px;
  --z-index: 12;
  animation-delay: 0s; 
}
.card:nth-child(13) { 
  --initial-x: 40px;
  --z-index: 13;
  animation-delay: 0s; 
}
.card:nth-child(14) { 
  --initial-x: 50px;
  --z-index: 14;
  animation-delay: 0s; 
}
.card:nth-child(15) { 
  --initial-x: 60px;
  --z-index: 15;
  animation-delay: 0s; 
}
.card:nth-child(16) { 
  --initial-x: 70px;
  --z-index: 16;
  animation-delay: 0s; 
}
.card:nth-child(17) { 
  --initial-x: 80px;
  --z-index: 17;
  animation-delay: 0s; 
}

/* 根据方向设置最终位置 */
.card[style*="--direction: 0"] { 
  --final-x: 0px;
  --final-y: 300px; /* 向下移动，扩大2倍 */
}
.card[style*="--direction: 1"] { 
  --final-x: 680px;
  --final-y: 0px; /* 向右移动，扩大3倍 */
}
.card[style*="--direction: 2"] { 
  --final-x: 0px;
  --final-y: -240px; /* 向上移动，扩大2倍 */
}
.card[style*="--direction: 3"] { 
  --final-x: -680px;
  --final-y: 0px; /* 向左移动，扩大3倍 */
}
.card[style*="--direction: -1"] { 
  --final-x: 0px;
  --final-y: 0px; /* 原地不动 */
}

/* 9秒后显示的视图样式 */
.after-animation-view {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
}

/* 底部视图上方的新视图 */
.above-bottom-view {
  position: absolute;
  bottom: 340px; /* 紧贴 bottom-view 顶部 */
  left: 50%;
  transform: translateX(-50%);
  width: 400px;
  height: 100px;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
}

.above-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.hint-text {
  color: #66ccff; /* 浅蓝色 */
  text-shadow: 0 1px 2px rgba(0,0,0,0.5);
  font-size: 16px;
}

.confirm-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  background: #66ccff; /* 浅蓝色背景 */
  color: #ffffff; /* 白色文字 */
  cursor: pointer;
}

.confirm-btn:hover {
  background: #55c3fb;
}

/* 底部子视图样式 */
.bottom-view {
  position: absolute;
  bottom: 0px;
  left: 50%;
  transform: translateX(-50%);
  width: 1300px;
  height: 340px;
  background: transparent;
  overflow-x: auto;
  overflow-y: hidden;
  white-space: nowrap;
}

/* 隐藏滚动条 */
.bottom-view::-webkit-scrollbar {
  display: none;
}

.bottom-view {
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

/* 角色图片容器样式 */
.charactor-images-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  gap: 10px;

}

/* 角色图片项样式 */
.charactor-image-item {
  position: relative;
  flex-shrink: 0;
  width: 210px;
  height: 330px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  transition: transform 0.3s ease;
  cursor: pointer;
  border: 3px solid transparent;
}

.owner-badge {
  position: absolute;
  top: 6px;
  left: 6px;
  background: rgba(144, 238, 144, 0.9); /* 浅绿色 */
  color: #fff; /* 白色小字 */
  font-size: 12px;
  line-height: 1;
  padding: 4px 6px;
  border-radius: 4px;
  z-index: 2;
}


/* 选中状态的黄色边框 */
.charactor-image-item.selected {
  border: 3px solid #ffd700;
  box-shadow: 0 0 15px rgba(255, 215, 0, 0.5);
}

.charactor-image-item.selected-teammate {
  border: 3px solid #9b59b6; /* 紫色边框 */
  box-shadow: 0 0 15px rgba(155, 89, 182, 0.5);
}

/* 角色图片样式 */
.charactor-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

/* 左下角自己角色圆形样式 */
.help-button {
  position: absolute;
  bottom: 20px;
  left: 20px;
  width: 150px;
  height: 150px;
  background: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  z-index: 1001;
}

.question-mark {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  user-select: none;
}
</style>
